import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: SliverGridExample());
  }
}

class SliverGridExample extends StatefulWidget {
  @override
  _SliverGridExampleState createState() => _SliverGridExampleState();
}

class _SliverGridExampleState extends State<SliverGridExample> {
  List<int> items = List.generate(20, (index) => index);

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: [
        SliverGrid(
          delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
              if (index == items.length) {
                // 加载更多
                Future.delayed(Duration(seconds: 1), () {
                  setState(() {
                    items.addAll(List.generate(10, (i) => items.length + i));
                  });
                });
                return Center(child: CircularProgressIndicator());
              }
              return Container(
                color: Colors.primaries[index % Colors.primaries.length]
                [100 * ((index % 9) + 1)],
                child: Center(child: Text('Item $index')),
              );
            },
            childCount: items.length + 1,
          ),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
          ),
        ),
      ],
    );
  }
}
